package cn.com.qc.main;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.qc.R;
import cn.com.qc.adapter.PopWindowsAdapter;
import cn.com.qc.app.App;
import cn.com.qc.bean.CityBean;
import cn.com.qc.bean.UserIntroInfo;
import cn.com.qc.help.Helps;
import cn.com.qc.help.NetUrl;
import cn.com.qc.javabean.NewsInfo;
import cn.com.qc.view.GlideImageLoader;
import cn.com.qc.yinter.EditIntroDataListener;
import cn.com.qc.ypresenter.EditIntroductionPresenter;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static android.util.TypedValue.COMPLEX_UNIT_DIP;


public class EditIntroductionActivity extends YBaseActivity<EditIntroductionPresenter, EditIntroductionActivity> implements EditIntroDataListener {

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.save)
    TextView save;
    @BindView(R.id.icon)
    ImageView icon;

    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.sex)
    EditText sex;
    @BindView(R.id.outYear)
    EditText outYear;
    @BindView(R.id.maxEdu)
    EditText maxEdu;
    @BindView(R.id.nature)
    EditText nature;
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.phoneText)
    TextView phoneText;
    @BindView(R.id.email)
    EditText email;

    @BindView(R.id.city)
    TextView city;

    @BindView(R.id.school)
    EditText school;
    @BindView(R.id.major)
    EditText major;
    @BindView(R.id.beginDate)
    EditText beginDate;
    @BindView(R.id.graduateDate)
    EditText graduateDate;
    @BindView(R.id.sno)
    EditText sno;

    @BindView(R.id.position)
    EditText position;
    @BindView(R.id.enterDate)
    EditText enterDate;
    @BindView(R.id.endDate)
    EditText endDate;
    @BindView(R.id.workContent)
    EditText workContent;

    private Integer experience_id = 0;
    private Integer education_id = 0;

    @Override
    public EditIntroductionPresenter getPresenter() {
        return new EditIntroductionPresenter();
    }

    @Override
    public int getResId() {
        return R.layout.activity_edit_self_info;
    }

    String studentId;
    App app;

    private String image_url = "";
    @Override
    public void init() {
        title.setText("编辑简历");
        save.setVisibility(View.VISIBLE);
        initImagePicker();
        Bundle bundle = getIntent().getExtras();
        String phone = bundle.getString("phone");
        studentId = bundle.getString("studentId");
        UserIntroInfo userIntroInfo = (UserIntroInfo) bundle.getSerializable("object");
    //    studentId = "730cc0f9-20e4-46d3-940b-08840ba5f2dd";
        this.phoneText.setText(phone);
        app = (App) getApplication();
        getUserInfo();
    }

    public void getUserInfo() {
        app = (App) getApplication();
        OkGo.<String>post(NetUrl.DNS + NetUrl.GetInfo)
                .tag(this)
                .params("id", app.id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            Log.d("用户信息界面",jsonObject.toString());
                            int infoCode = jsonObject.getInt("status");
                            if (infoCode == 0) {
                                JSONObject data = jsonObject.optJSONObject("data");
                                JSONObject user = data.optJSONObject("user");
                                name.setText(user.optString("realName"));
                                Integer sexs = user.optInt("sex");
                                if (sexs == 0){
                                    sex.setText("女");
                                }else{
                                    sex.setText("男");
                                }
                                outYear.setText(user.optString("birth"));
                                city.setText(user.optString("city"));
                                phone.setText(user.optString("phone"));
                                email.setText(user.optString("email"));
                                String headImg = user.optString("photo");
                                nature.setText(user.optString("nature"));
                                int width = (int) TypedValue.applyDimension(COMPLEX_UNIT_DIP,58,getResources().getDisplayMetrics());
                                p.intoCircle(EditIntroductionActivity.this,headImg,icon, R.mipmap.head_img,width,width);
                                JSONArray education = data.optJSONArray("education");
                                for (int i = 0;i<education.length();i++){
                                    JSONObject education_item = education.optJSONObject(i);
                                    education_id = education_item.optInt("id");
                                    school.setText(education_item.optString("college"));
                                    major.setText(education_item.optString("major"));
                                    beginDate.setText(education_item.optString("start"));
                                    graduateDate.setText(education_item.optString("end"));
                                    sno.setText(education_item.optString("sno"));
                                }
                                JSONArray experience = data.optJSONArray("experience");
                                for (int i = 0;i<experience.length();i++){
                                    JSONObject experience_item = experience.optJSONObject(i);
                                    experience_id = experience_item.optInt("id");
                                    position.setText(experience_item.optString("jobName"));
                                    enterDate.setText(experience_item.optString("start"));
                                    endDate.setText(experience_item.optString("end"));
                                    workContent.setText(experience_item.optString("content"));
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    @OnClick({R.id.returns, R.id.save, R.id.iconLinear, R.id.city})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.returns:
                finish();
                break;
            case R.id.save:
                save();
                break;
            case R.id.iconLinear:
                openActivityForResult(ImageGridActivity.class, 100);
                break;
            case R.id.city:
                if (isLoadCompleted) {
                    showCity();
                } else {
                    p.getAllCity(NetUrl.AllCity);
                }
                break;
        }
    }

    private void save() {
        String name = getText(this.name);
        String sex = getText(this.sex);
        if(!sex.equals("")){
            if(sex.equals("男")){
                sex = "1";
            }else if(sex.equals("女")){
                sex = "0";
            }else{
                Helps.toast(this,"性别不合要求");
            }
        }
        String outYear = getText(this.outYear);
        //    String maxEdu = getText(this.maxEdu);
        String nature = getText(this.nature);
        String phone = getText(this.phoneText);
        String email = getText(this.email);

        String city = getText(this.city);

        String school = getText(this.school);//major graduateDate maxEdu1
        String major = getText(this.major);
        String beginDate = getText(this.beginDate);
        String graduateDate = getText(this.graduateDate);
        String sno = getText(this.sno);
        String position = getText(this.position);
        String enterDate = getText(this.enterDate);
        String endDate = getText(this.endDate);
        String workContent = getText(this.workContent);
        update_info(name,sex,outYear, nature, phone, email, city,school,major,beginDate,graduateDate,sno,position,enterDate,endDate,workContent);
    }

    private String getText(EditText editText) {
        String content = editText.getText().toString().trim();
        return content;
    }

    private String getText(TextView editText) {
        String content = editText.getText().toString().trim();
        return content;
    }

    private boolean checkTimeForm(String time) {
        boolean b = time.matches("^[0-9]{4}\\.[0-9]{1,2}\\.[0-9]{1,2}$");
        return b;
    }

    private long format(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
        Date date;
        try {
            date = format.parse(time);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    boolean isLoadCompleted = false;
    List<String> citys = new ArrayList<>();

    private void showCity() {
        View view = LayoutInflater.from(this).inflate(R.layout.popwindow_city_item, null);
        final PopupWindow popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        ListView listView = (ListView) view.findViewById(R.id.listView);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) listView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels * 2 / 3;
        params.height = getResources().getDisplayMetrics().heightPixels * 1 / 2;
        listView.setLayoutParams(params);
        PopWindowsAdapter adapter = new PopWindowsAdapter(this, citys, R.layout.popwindow_text_layout1);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupWindow.dismiss();
                city.setText(citys.get(position));
            }
        });
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xffffffff));
        popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        GlideImageLoader imageLoader = new GlideImageLoader();
        imagePicker.setImageLoader(imageLoader);   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setSaveRectangle(false); //是否按矩形区域保存
        imagePicker.setSelectLimit(1);    //选中数量限制
    }

    String path;

    String fileName;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                fileName = images.get(0).name;
                path = images.get(0).path;
                Log.d("上传图片",path);
                File file = new File(path);
                OkGo.<String>post(NetUrl.DNS + NetUrl.upImage)
                        .tag(this)
                        .params("image", file)
                        .isMultipart(true)
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                try {
                                    JSONObject jsonObject = new JSONObject(response.body());
                                    Log.d("上传图片",jsonObject.toString());
                                    int infoCode = jsonObject.getInt("status");
                                    if (infoCode == 0) {
                                        JSONObject data = jsonObject.optJSONObject("data");
                                        image_url = data.optString("url");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                long size = images.get(0).size;
                int width = images.get(0).width;
                String mimeType = images.get(0).mimeType;
                long addTime = images.get(0).addTime;
                int w = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 58, getResources().getDisplayMetrics());
                p.intoLocalCicle(this, path, icon, R.mipmap.head_img, w);
            } else {
                Helps.toast(this, "没有数据");
            }
        }
    }

    @Override
    public void onCitySuccess(List<String> citys) {
        isLoadCompleted = true;
        this.citys.clear();
        if (citys != null) {
            this.citys.addAll(citys);
        }
        showCity();
    }

    @Override
    public void onCityError() {
        Helps.toast(this, "城市信息获取失败!");
    }

    @Override
    public void onUpImageError() {
        Helps.toast(this, "保存失败");
    }

    @Override
    public void updateIntroSuccess(String infoCode, String message) {
        Helps.toast(this, message);
    }

    @Override
    public void updateIntroError() {
        Helps.toast(this, "保存失败");
    }

    public void update_info(String RealName,String Sex,String Birth,String Nature,String Phone,String Email,String City,String school,String major,String beginDate,String graduateDate,String sno,String position,String enterDate,String endDate,String workContent){
        JSONObject user_json = new JSONObject();
        JSONObject user_info = new JSONObject();
        JSONObject education_item = new JSONObject();
        JSONArray education = new JSONArray();
        JSONObject experience_item = new JSONObject();
        JSONArray experience = new JSONArray();
        try {
            user_info.put("id", Integer.parseInt(app.id));
            user_info.put("realName", RealName);
            if (!image_url.equals("")){
                user_info.put("photo",image_url);
            }
            user_info.put("sex",Sex);
            user_info.put("birth", Birth);
            user_info.put("nature",Nature);
            user_info.put("phone", Phone);
            user_info.put("email",Email);
            user_info.put("city",City);
            user_json.put("user",user_info);
            if (education_id != 0){
                education_item.put("id", education_id);
            }
            education_item.put("userId", Integer.parseInt(app.id));
            education_item.put("college", school);
            education_item.put("start", beginDate);
            education_item.put("end", graduateDate);
            education_item.put("major", major);
            education_item.put("sno", sno);
            education.put(education_item);
            user_json.put("educations",education);

            if (experience_id != 0){
                experience_item.put("id", experience_id);
            }
            experience_item.put("userId", Integer.parseInt(app.id));
            experience_item.put("jobName", position);
            experience_item.put("start", enterDate);
            experience_item.put("end", endDate);
            experience_item.put("content", workContent);
            experience.put(experience_item);
            user_json.put("experiences",experience);
            Log.d("封装数据是", "json1: " + user_json);
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(JSON, user_json.toString());
            OkGo.<String>post(NetUrl.DNS + NetUrl.UpdateuserInfo)
                    .upRequestBody(body)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            Helps.toast(EditIntroductionActivity.this,"用户信息修改成功");
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);

                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
